package com.the_ring.chapter07.fragment;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.the_ring.chapter07.R;
import com.the_ring.chapter07.adapter.BillItemAdapter;
import com.the_ring.chapter07.bean.BillInfo;
import com.the_ring.chapter07.database.DatabaseHelper;

import java.util.List;

public class MonthFragment extends Fragment {

    protected View mView;
    protected Context mContext;

    private ListView billLv;
    private TextView inputTv;
    private TextView outputTv;
    private TextView restTv;
    private BillItemAdapter itemAdapter;
    private int month;
    private int year;

    public static MonthFragment newInstance(int month, int year) {
        Bundle args = new Bundle();                     // 创建一个新包裹
        args.putInt("month", month);                    // 往包裹中存入数据
        args.putInt("year", year);
        MonthFragment fragment = new MonthFragment();   // 创建该碎片的一个实例
        fragment.setArguments(args);                    // 把包裹塞给碎片
        return fragment;                                // 返回碎片实例
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mContext = getActivity();
        if (getArguments() != null) {
            month = getArguments().getInt("month");
            year = getArguments().getInt("year");
        }
        mView = inflater.inflate(R.layout.month_fragment, container, false);
        billLv = mView.findViewById(R.id.lv_bill);
        inputTv = mView.findViewById(R.id.tv_input);
        outputTv = mView.findViewById(R.id.tv_output);
        restTv = mView.findViewById(R.id.tv_rest);

        initData();

        return mView;
    }

    private void initData() {
        List<BillInfo> infoList = DatabaseHelper.getInstance(mContext).queryByMonth(year, month);

        itemAdapter = new BillItemAdapter(mContext, infoList);
        billLv.setAdapter(itemAdapter);
        billLv.setOnItemClickListener(itemAdapter); // 列表项点击事件
        billLv.setOnItemLongClickListener(itemAdapter); // 长按点击事件

        int input = 0;
        int output = 0;
        int rest = 0;
        for (BillInfo info : infoList) {
            if (info.type == 1) {
                input += info.money;
            } else {
                output += info.money;
            }
            rest += info.type * info.money;
        }
        inputTv.setText("收入" + String.valueOf(input) + "元");
        outputTv.setText("支出" + String.valueOf(output) + "元");
        restTv.setText("余额" + String.valueOf(rest) + "元");
    }
}
